package com.sky.controller.user;


import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Api("用户接口")
@Slf4j
@RestController
@RequestMapping("/user/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    JwtProperties jwtProperties;

    /**
     * 用户登录功能
     * @param userLoginDTO
     * @return
     */
    @PostMapping ("/login")
    @ApiOperation("登录功能")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("微信登录用户：{}",userLoginDTO.getCode());
        //1. 查询用户
        User user=userService.login(userLoginDTO);

        //2. 生成token
        Long id = user.getId();
        Map<String,Object> claims=new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,id);
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        //3. 拷贝属性
        UserLoginVO loginVO = UserLoginVO.builder()
                .id(id)
                .token(token)
                .openid(user.getOpenid())
                .build();

        //4. 返回数据
        return Result.success(loginVO);
    }
}
